package main

import (
	"illusion"
	"strconv"
	"fmt"

	"strings"
)

type Title struct {
	Title string
}
type Poem struct {
	illusion.Model
	//ID int
	Name string
	Author_id int
	Text string
	Like int
	View int
	//DeletedAt mysql.NullTime
	//CreatedAt  time.Time
	//UpdatedAt  time.Time
}

func notFound(c *illusion.Context) {
	c.View("404.html", illusion.Values{"Title": "你是傻逼吗"})
}

func b()string{
	return "bbbbb"
}

func main() {
	b := "fdfgdsfdsdf&sdf"
	arr := strings.Split(b, "&")
	leftB := strings.Join(arr[:len(arr)-1], "&")
	fmt.Println(leftB)
	isDebug := illusion.EnvBool("debug", false)
	if isDebug {
		fmt.Println("is debug")
	}
	session := illusion.EnvString("session", "file")
	fmt.Println("session:" + session)

	app := illusion.App()
	var p Poem

	//os.Exit(0)
	//fmt.Println("conf.Mysql.Prod:" + conf.Cache.Use)
	//fmt.Printf("---conf dump: %v", illusion.GetConfig())
	//app.Unbind(illusion.UNBIND_TEMPLATE)
	app.NoFoundHandler(notFound)
	//位于根目录下

	index := illusion.BluePrint("/", "index")

	index.Before(func(c *illusion.Context) {
		//fmt.Println("到了Before..")
		session := c.Session()
		name := session.Read("name")
		if name == "" {
			session.Store("name", "你就吹吧")
		}

		db := illusion.Manager()
		db.First(&p, 1)

		fmt.Println(p.Name)
	})

	index.Get("/", func(c *illusion.Context){
		c.View("index.html", illusion.Values{"Title": "Laravel"})
	})

	index.Get("/index", func(c *illusion.Context) {
		session := c.Session()
		//var val string
		//var err error
		name := c.Query("name")
		session.Store("name", name)

		name = session.Read("name")


		//c.Cache().DefaultFuncGet("bb", b)
		cache := illusion.ECache()
		cache.Set("bb", "leonard")


		dCache := cache.Get("bb")

		c.View("index.html", illusion.Values{"Title": name, "Cache": dCache})
	})

	index.Get("/redirect", func(c *illusion.Context) {
		c.Redirect("/index")
	})

	ping := illusion.BluePrint("/ping", "ping")

	ping.Get("/", func(c *illusion.Context) {
		c.String(200, "pong too....")
	})
	ping.Get("/string", func(c *illusion.Context) {
		c.String(200, "pong")
	})
	ping.Get("/json", func(c *illusion.Context) {
		c.Json(200,illusion.Values{"Title": "what the fuck"})
	})
	ping.Get("/kamila", func(c *illusion.Context) {
		c.Json(200, illusion.Values{"Title": "Shenm"})
	})

	type V struct {
		Name string `validate:"min=3,max=4"`
		Age int  `validate:"min=20"`
	}

	ping.Get("/validate", func(c *illusion.Context) {
		age,_ := strconv.Atoi(c.Query("age"))
		v := &V{Name: c.Query("name"), Age: age}
		if err := c.Validate(v);err!=nil{
			c.Json(200, illusion.Values{"Name": v.Name, "Err": err.Error()})
			return
		}
		c.String(200, "It's Ok")
	})
	app.Register(index)
	app.Register(ping)
	app.Run(":8080")
}
